package com.tiantianyuegou.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tiantianyuegou.activity.BaseActivity;
import com.tiantianyuegou.R;
import com.tiantianyuegou.adapter.ProductDespAdapter;
import com.tiantianyuegou.constant.Constant;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.http.SPHelper;
import com.tiantianyuegou.model.ProductImgeModel;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.MultipartEntity;
import com.tiantianyuegou.util.PictureUtil;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 申请退款
 */
public class RefundActivity extends BaseActivity implements View.OnClickListener {

    private ImageView img_title;
    private TextView text_title, text_menu;

    private LinearLayout linear_shenqingfuwu, linear_tuihuoyuanyin, linear_huowuzhuangtai, linear_gone, linear_add_img;
    private Button btn_tijiaoshenqing;
    private ImageView img_reason_one, img_reason_two, img_reason_three;
    private TextView text_shenqingfuwu, text_tuihuoyuanyin, text_huowuzhuangtai, text_tuikuanjine;
    private EditText edit_tuikuanshuoming;

    private String toId, money, type, toStatus = "1";
    private String TAG = "RefundActivity";

//    private ArrayList<ProductImgeModel> mData;
//    private ProductDespAdapter mAdapter;

    private List<String> mPicUrl;

    private Dialog mAddDialog, mDeleteDialog;
    private String mDesp;
    private Bitmap mBitmap;
    private EditText mEt_desp;
    private String mReasonId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_refund);
        initViews();
    }

    @Override
    public void findViewByIds() {
        text_title = (TextView) findViewById(R.id.text_title);
        img_title = (ImageView) findViewById(R.id.img_title);
        text_title.setText(R.string.refund_title);

        linear_shenqingfuwu = (LinearLayout) findViewById(R.id.linear_shenqingfuwu);
        linear_tuihuoyuanyin = (LinearLayout) findViewById(R.id.linear_tuihuoyuanyin);
        linear_huowuzhuangtai = (LinearLayout) findViewById(R.id.linear_huowuzhuangtai);
        linear_gone = (LinearLayout) findViewById(R.id.linear_gone);
        linear_add_img = (LinearLayout) findViewById(R.id.linear_add_img);

        text_shenqingfuwu = (TextView) findViewById(R.id.text_shenqingfuwu);
        text_tuihuoyuanyin = (TextView) findViewById(R.id.text_tuihuoyuanyin);
        text_huowuzhuangtai = (TextView) findViewById(R.id.text_huowuzhuangtai);
        text_tuikuanjine = (TextView) findViewById(R.id.text_tuikuanjine);

        img_reason_one = (ImageView) findViewById(R.id.img_reason_one);
        img_reason_two = (ImageView) findViewById(R.id.img_reason_two);
        img_reason_three = (ImageView) findViewById(R.id.img_reason_three);

        edit_tuikuanshuoming = (EditText) findViewById(R.id.edit_tuikuanshuoming);

        btn_tijiaoshenqing = (Button) findViewById(R.id.btn_tijiaoshenqing);
    }

    @Override
    public void initListener() {
        img_title.setOnClickListener(this);
        linear_shenqingfuwu.setOnClickListener(this);
        linear_tuihuoyuanyin.setOnClickListener(this);
        linear_huowuzhuangtai.setOnClickListener(this);
        linear_gone.setOnClickListener(this);
        linear_add_img.setOnClickListener(this);
        linear_huowuzhuangtai.setVisibility(View.GONE);
        linear_gone.setVisibility(View.GONE);
        btn_tijiaoshenqing.setOnClickListener(this);
        img_reason_two.setOnClickListener(this);
        img_reason_one.setOnClickListener(this);
        img_reason_three.setOnClickListener(this);
    }

    @Override
    public void initData() {
        mPicUrl = new ArrayList<>();
        toId = getIntent().getStringExtra("toId");
        money = getIntent().getStringExtra("money");
//        type = getIntent().getStringExtra("type");
//        toStatus = getIntent().getStringExtra("toStatus");
        text_tuikuanjine.setText(money);
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    private void loadTuiKuan(String mPicUrl) {

        final LoadingDialog loadingDialog = new LoadingDialog(this);
        loadingDialog.setMsg("正在申请退款");
        loadingDialog.show();
        RequestParams params = new RequestParams();
        params.addBodyParameter("tmId", SPHelper.getTmId());
        params.addBodyParameter("toId", toId);
        params.addBodyParameter("money", money);

        if ("仅退货".equals(text_shenqingfuwu.getText().toString())) {
            type = "2";
        } else if ("退货退款".equals(text_shenqingfuwu.getText().toString())) {
            type = "1";
            toStatus="2";//此时必定为已收到货
        }
        params.addBodyParameter("type", type);

        params.addBodyParameter("wordId", mReasonId);

        if ("未收到货".equals(text_huowuzhuangtai.getText().toString())) {
            toStatus = "1";
        } else if ("已收到货".equals(text_huowuzhuangtai.getText().toString())) {
            toStatus = "2";
        }

        params.addBodyParameter("productStatus", toStatus);
        params.addQueryStringParameter("desp", edit_tuikuanshuoming.getText().toString());
        params.addBodyParameter("file", mPicUrl);
        Log.e("TAG", "params: tmId:" + SPHelper.getTmId() + ":toId:" + toId + ":money:" + money + ":type：" + type
                + ":wordId:" + mReasonId + ":productStatuc:" + toStatus + ":desp:" + edit_tuikuanshuoming.getText().toString()
                + ":file:" + mPicUrl);

        loadData(HttpRequest.HttpMethod.POST, ApiDefine.ORDER_REFUND, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                loadingDialog.dismiss();
                String response = responseInfo.result;
                Log.e(TAG, "submit data response:" + response);
                try {
                    JSONObject object = new JSONObject(response);
                    if ("100".equals(object.getString("code"))) {
                        showMsg("退货成功");
                        finish();
                    } else {
                        showMsg(object.getString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    showMsg("解析异常");
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                loadingDialog.dismiss();
                showMsg("当前网络不可用,请检查您的网络设置");
                Log.e("TAG", "submit data failure:" + s);
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_title:
                finish();
                break;
            case R.id.linear_shenqingfuwu:
                Intent linear_shenqingfuwu = new Intent(RefundActivity.this, RefundOptionActivity.class);
                linear_shenqingfuwu.putExtra("type", "1");
                startActivityForResult(linear_shenqingfuwu, Constant.GET_SERVICE_REQUEST);
                break;
            case R.id.linear_tuihuoyuanyin:

                Intent linear_tuihuoyuanyin = new Intent(RefundActivity.this, RefundOptionActivity.class);
                linear_tuihuoyuanyin.putExtra("type", "2");
                startActivityForResult(linear_tuihuoyuanyin, Constant.GET_REASON_REQUEST);
                break;
            case R.id.linear_huowuzhuangtai:
                Intent linear_huowuzhuangtai = new Intent(RefundActivity.this, RefundOptionActivity.class);
                linear_huowuzhuangtai.putExtra("type", "3");
                startActivityForResult(linear_huowuzhuangtai, Constant.GET_STATUS_REQUEST);

                break;
            case R.id.linear_gone:

                break;
            case R.id.linear_add_img:
                if (mPicUrl.size() <= 3) {
                    addDialog();
                } else {

                }
                break;
            case R.id.img_reason_one:
                deleteDialog(0);
                break;
            case R.id.img_reason_two:
                deleteDialog(1);
                break;
            case R.id.img_reason_three:
                deleteDialog(2);
                break;
            case R.id.btn_tijiaoshenqing:
                StringBuffer picUrl = new StringBuffer();
                for (int i = 0; i < mPicUrl.size(); i++) {
                    picUrl.append(mPicUrl.get(i)).append(",");
                }
                if ("申请服务".equals(text_shenqingfuwu.getText().toString())) {
                    showMsg("请先选择申请服务");
                    return;
                } else if ("退货原因".equals(text_tuihuoyuanyin.getText().toString())) {
                    showMsg("请先选择退货原因");
                    return;
                } else if ("仅退货".equals(text_shenqingfuwu.getText().toString())) {
                    if ("货物状态".equals(text_huowuzhuangtai.getText().toString())) {
                        showMsg("请先选择货物状态");
                        return;
                    } else {
                        if (picUrl.length() == 0) {
                            loadTuiKuan("");
                        } else {
                            loadTuiKuan(picUrl.substring(0, picUrl.length() - 1));
                        }
                    }
                } else {
                    if (picUrl.length() == 0) {
                        loadTuiKuan("");
                    } else {
                        loadTuiKuan(picUrl.substring(0, picUrl.length() - 1));
                    }
                }
                break;

            default:
                break;
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            Intent intent = new Intent("com.android.camera.action.CROP");
            Uri data2 = null;
            if (data == null) {
                data2 = PictureUtil.getImageUri();
            } else {
                data2 = data.getData();
            }
            if (requestCode == Constant.MEDIA_CROP_REQUEST_CODE) {
                mBitmap = decodeUriAsBitmap(imageFilePath);// decode
                uploadBmp(mBitmap); //上传头像到服务器端
            } else if (requestCode == Constant.MEDIA_IMAGE_REQUEST_CODE) {
                if (data != null) {
                    imageFilePath = data.getData();
                    cropImageUri(imageFilePath, 300, 300,
                            Constant.MEDIA_CROP_REQUEST_CODE);
                }
            } else if (requestCode == Constant.MEDIA_CAMERA_REQUEST_CODE) {
                cropImageUri(imageFilePath, 300, 300, Constant.MEDIA_CROP_REQUEST_CODE);
            } else if (requestCode == PictureUtil.PHOTO_PICKED_WITH_DATA) {
                intent.setDataAndType(data2, "image/*");
                intent.putExtra("crop", true);
                // 设置裁剪尺寸
                intent.putExtra("aspectX", 1);
                intent.putExtra("aspectY", 1);
                intent.putExtra("outputX", 300);
                intent.putExtra("outputY", 300);
                intent.putExtra("return-data", true);
                intent.putExtra(MediaStore.EXTRA_OUTPUT,
                       PictureUtil.getImageCaiUri());
                startActivityForResult(intent, PictureUtil.PHOTO_CROP);
            } else if (requestCode == PictureUtil.PHOTO_CROP) {
                Bundle bundle = data.getExtras();
                Bitmap myBitmap = (Bitmap) bundle.get("data");
                mBitmap = PictureUtil.comp(myBitmap);

                String fileName = PictureUtil.getCharacterAndNumber();
                File file = new File(PictureUtil.PHOTO_DIR, fileName + ".png");
               PictureUtil.saveMyBitmap(mBitmap, file);
                uploadBmp(mBitmap);
            }
            mAddDialog.dismiss();
        } else if (requestCode == Constant.GET_SERVICE_REQUEST) {
            if (resultCode == Constant.GET_SERVICE_RESULT) {
                String content = data.getStringExtra("data");
                if (content != null && !"".equals(content)) {
                    text_shenqingfuwu.setText(content);
                    if ("仅退货".equals(content)) {
                        linear_huowuzhuangtai.setVisibility(View.VISIBLE);
                        linear_gone.setVisibility(View.GONE);
                    } else {
                        linear_huowuzhuangtai.setVisibility(View.GONE);
                        linear_gone.setVisibility(View.VISIBLE);
                    }
                } else {
                    text_shenqingfuwu.setText("申请服务");
                }
            }
        } else if (requestCode == Constant.GET_REASON_REQUEST) {
            if (resultCode == Constant.GET_REASON_RESULT) {
                String content = data.getStringExtra("data");
                mReasonId = data.getIntExtra("id", 0) + "";
                if (content != null && !"".equals(content)) {
                    text_tuihuoyuanyin.setText(content);
                } else {
                    text_tuihuoyuanyin.setText("退货原因");
                }
            }
        } else if (requestCode == Constant.GET_STATUS_REQUEST) {
            if (resultCode == Constant.GET_STATUS_RESULT) {
                String content = data.getStringExtra("data");
                if (content != null && !"".equals(content)) {
                    text_huowuzhuangtai.setText(content);
                } else {
                    text_huowuzhuangtai.setText("获取状态");
                }
            }
        }
    }


    //删除
    private void deleteDialog(final int position) {
        View view = getLayoutInflater().inflate(R.layout.dialog_head, null);
        mDeleteDialog = new Dialog(this, R.style.transprentFrameWindowStyle);
        mDeleteDialog.setContentView(view, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT));
        Window window = mDeleteDialog.getWindow();
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        mDeleteDialog.onWindowAttributesChanged(wl);
        mDeleteDialog.setCanceledOnTouchOutside(true);

        Button dialog_photograph, dialog_photo, dialog_quit;
        dialog_photo = (Button) view.findViewById(R.id.dialog_photo);
        dialog_photo.setText("取消");
        dialog_photograph = (Button) view.findViewById(R.id.dialog_photograph);
        dialog_photograph.setText("删除");

        dialog_quit = (Button) view.findViewById(R.id.dialog_quit);
        dialog_quit.setVisibility(View.GONE);
        //删除
        dialog_photograph.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                deltePic(position);
                hidePic(position);
                mDeleteDialog.dismiss();
            }
        });

        dialog_photo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mDeleteDialog.dismiss();
            }
        });
        mDeleteDialog.show();
    }

    private void deltePic(int position) {
        if (img_reason_one.getVisibility() == View.VISIBLE
                && img_reason_two.getVisibility() == View.VISIBLE
                && img_reason_three.getVisibility() == View.VISIBLE) {
            mPicUrl.remove(position);
        } else if (img_reason_one.getVisibility() == View.GONE
                && img_reason_two.getVisibility() == View.VISIBLE
                && img_reason_three.getVisibility() == View.VISIBLE) {
            mPicUrl.remove(position - 1);
        } else if (img_reason_one.getVisibility() == View.VISIBLE
                && img_reason_two.getVisibility() == View.GONE
                && img_reason_three.getVisibility() == View.VISIBLE) {
            if (position == 2) {
                mPicUrl.remove(position - 1);
            } else {
                mPicUrl.remove(position);
            }
        } else if (img_reason_one.getVisibility() == View.VISIBLE
                && img_reason_two.getVisibility() == View.VISIBLE
                && img_reason_three.getVisibility() == View.GONE) {
            mPicUrl.remove(position);
        } else if (img_reason_one.getVisibility() == View.GONE
                && img_reason_two.getVisibility() == View.GONE
                && img_reason_three.getVisibility() == View.VISIBLE) {
            mPicUrl.clear();
        } else if (img_reason_one.getVisibility() == View.GONE
                && img_reason_two.getVisibility() == View.VISIBLE
                && img_reason_three.getVisibility() == View.GONE) {
            mPicUrl.clear();
        } else if (img_reason_one.getVisibility() == View.VISIBLE
                && img_reason_two.getVisibility() == View.GONE
                && img_reason_three.getVisibility() == View.GONE) {
            mPicUrl.clear();
        }
    }

    private void hidePic(int position) {
        linear_add_img.setVisibility(View.VISIBLE);
        switch (position) {
            case 0:
                img_reason_one.setVisibility(View.GONE);
                break;
            case 1:
                img_reason_two.setVisibility(View.GONE);
                break;
            case 2:
                img_reason_three.setVisibility(View.GONE);
                break;
        }
    }

    private Uri imageFilePath;

    //添加
    private void addDialog() {
        View view = getLayoutInflater().inflate(R.layout.dialog_head, null);
        mAddDialog = new Dialog(this, R.style.transprentFrameWindowStyle);
        mAddDialog.setContentView(view, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT));
        Window window = mAddDialog.getWindow();
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        mAddDialog.onWindowAttributesChanged(wl);
        mAddDialog.setCanceledOnTouchOutside(true);

        Button dialog_photograph, dialog_photo, dialog_quit;

        dialog_photograph = (Button) view.findViewById(R.id.dialog_photograph);
        dialog_photo = (Button) view.findViewById(R.id.dialog_photo);
        dialog_quit = (Button) view.findViewById(R.id.dialog_quit);

        /**
         * 系统相机
         */
        dialog_photograph.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // 调用系统相机
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                ContentValues values = new ContentValues(3);
                values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                imageFilePath = RefundActivity.this.getContentResolver()
                        .insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                values);

                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageFilePath);
                startActivityForResult(intent, Constant.MEDIA_CAMERA_REQUEST_CODE);

            }
        });

        /**
         * 系统相册
         */
        dialog_photo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // 调用系统相册
              PictureUtil.doPickPhotoFromGallery(RefundActivity.this);
            }
        });

        dialog_quit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mAddDialog.dismiss();
            }
        });
        mAddDialog.show();
    }


    private void uploadBmp(Bitmap b) {
        new UploadTask().execute(b);
    }

    private class UploadTask extends AsyncTask<Bitmap, String, String> {
        LoadingDialog loadingDialog = null;

        public UploadTask() {
            loadingDialog = new LoadingDialog(RefundActivity.this);
            loadingDialog.setMsg("正在上传图片");
            loadingDialog.show();
        }

        protected String doInBackground(Bitmap... bitmaps) {
            if (bitmaps[0] == null)
                return null;

            Bitmap bitmap = bitmaps[0];
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            InputStream in = new ByteArrayInputStream(stream.toByteArray());

            DefaultHttpClient httpclient = new DefaultHttpClient();
            ByteArrayOutputStream baos;
            try {
                HttpPost httppost = new HttpPost(ApiDefine.UPLOAD_PRODUCT_PIC); // server

                MultipartEntity reqEntity = new MultipartEntity();

                reqEntity.addPart("photo", System.currentTimeMillis() + ".jpg",
                        in);

                httppost.setEntity(reqEntity);

                System.out.println("requestLineInfo>>"
                        + httppost.getRequestLine());
                HttpResponse response = null;
                baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[8192];
                try {
                    response = httpclient.execute(httppost);
                    if (response != null) {
                        StatusLine statusLine = response.getStatusLine();
                        System.out.println(statusLine.getStatusCode());
                        if (statusLine != null
                                && statusLine.getStatusCode() == HttpStatus.SC_OK) {
                            InputStream is = response.getEntity().getContent();
                            baos.reset();
                            for (int len = is.read(buffer); len != -1; len = is
                                    .read(buffer)) {
                                baos.write(buffer, 0, len);
                            }
                            System.out.println(baos.toString());
                        }
                    }

                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    if (response != null)
                        System.out.println("responseInfo>>"
                                + response.getStatusLine().toString());
                } finally {

                }
            } finally {

            }

            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return baos.toString();
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            loadingDialog.dismiss();
            uploadAvaterResult(result);
        }
    }

    /**
     * 解析是否上传头像成功
     */
    private void uploadAvaterResult(String resultJson) {
        try {
            JSONObject bean = new JSONObject(resultJson);
            String code = bean.getString("code");
            if ("100".equals(code)) {
                String result = bean.getString("result");
                mPicUrl.add(result);
                showPic(mPicUrl.size());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void showPic(int size) {
        switch (size) {
            case 1:
                img_reason_one.setImageBitmap(mBitmap);
                img_reason_one.setVisibility(View.VISIBLE);
                break;
            case 2:
                if (img_reason_one.getVisibility() == View.GONE) {
                    img_reason_one.setImageBitmap(mBitmap);
                    img_reason_one.setVisibility(View.VISIBLE);
                } else {
                    img_reason_two.setImageBitmap(mBitmap);
                    img_reason_two.setVisibility(View.VISIBLE);
                }
                break;
            case 3:
                linear_add_img.setVisibility(View.GONE);
                if (img_reason_one.getVisibility() == View.GONE) {
                    img_reason_one.setImageBitmap(mBitmap);
                    img_reason_one.setVisibility(View.VISIBLE);
                } else if (img_reason_two.getVisibility() == View.GONE) {
                    img_reason_two.setImageBitmap(mBitmap);
                    img_reason_two.setVisibility(View.VISIBLE);
                } else {
                    img_reason_three.setImageBitmap(mBitmap);
                    img_reason_three.setVisibility(View.VISIBLE);
                }
                break;
        }
    }

    /**
     * bitmap 转换成字节
     */
    public byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    /**
     * Uri转化成Bmp
     */
    private Bitmap decodeUriAsBitmap(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver()
                    .openInputStream(uri));
        } catch (Throwable e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }

    /**
     * 裁剪图片
     */
    private void cropImageUri(Uri uri, int outputX, int outputY, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, requestCode);
    }
}
